#!/usr/bin/python2
import tornado.web
import tornado.websocket
import tornado.ioloop
import threading
import re
import os
from Globals import *

class MainHandler(tornado.web.RequestHandler):
	def get(self):
		self.render("interface.html")
 
class WebSocketHandler(tornado.websocket.WebSocketHandler):
	clients = []

	def open(self):
		self.clients.append(self)

	def on_close(self):
		self.clients.remove(self)

	def on_message(self, message):
		if re.match("^\++", message):
			hook.main.volumeUp()
		elif re.match("^\-+", message):
			hook.main.volumeDown()
		elif re.match("^%$", message):
			# self.write_message(u"" + str(hook.MP.get_percent_pos()))
			percent = str(hook.MP.command('pausing_keep_force get_percent_pos'))
			if '[]' not in percent:
				percent = re.search('\d+', percent).group(0)
				self.write_message(u"" + percent)
		elif re.match("^previous$", message):
			hook.main.skipSong(-1)
		elif re.match("^next$", message):
			hook.main.skipSong(1)
		elif re.match("^pause$", message):
			hook.MP.pause()
		elif re.match("^stop$", message):
			hook.main.stopPlaying()
		elif re.match("^yt", message):
			songParts = message.split("yt ")
			keywords = re.sub('[^0-9a-zA-Z ]', '', songParts[1])
			hook.main.playSong(keywords)
			self.broadcast(u""+hook.YT.title + " (" + hook.YT.duration + ")|_|"+keywords)
		elif re.match("^fc", message):
			songParts = message.split("fc ")
			keywords = re.sub('[^0-9a-zA-Z ]', '', songParts[1])
			hook.main.stopPlaying()
			hook.main.playSong(keywords)
			

	def broadcast(self, message):
		for client in self.clients:
			client.write_message(u"" + message)
settings = {
	"static_path": os.path.join(os.path.dirname(__file__), "static")
}
application = tornado.web.Application([
	(r"/", MainHandler),
	(r"/websocket", WebSocketHandler),
], **settings)

def run():
	t = StartServer()
	t.start()

class StartServer(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)

	def run(self):
		application.listen(8888)
		tornado.ioloop.IOLoop.instance().start()